package com.fanqwz.kotlinmvvm.common.util.rxjava.gson

import com.fanqwz.kotlinmvvm.common.util.log.loge
import com.google.gson.*
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.util.*

/**
 * Created by fanqwz on 2017/8/14.
 */

class GsonArrayNullAdapter<T> : JsonDeserializer<List<T>> {

    @Throws(JsonParseException::class)
    override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): List<T>? {
        if (json.isJsonArray || typeOfT is List<*>) {
            var arr: JsonArray?
            try {
                arr = json.asJsonArray
            } catch (e: Exception) {
                json.asJsonNull
                loge("deserialize: fail for $typeOfT, json=$json", e)
                return null
            }

            if (arr == null)
                return ArrayList<T>(0)

            if ((typeOfT as ParameterizedType).actualTypeArguments == null || typeOfT.actualTypeArguments.size == 0) {
                loge("deserialize: param not exist")
                return null
            }

            try {
                val list = ArrayList<T>(arr.size())
                for (e in arr) {
                    list.add(context.deserialize<T>(e, typeOfT.actualTypeArguments[0]))
                }

                return list
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }

        return null
    }

}
